import 'dart:async';
import 'dart:math';
import 'package:audioplayers/audioplayers.dart';
import '../models/song.dart';

// 播放模式枚举
enum PlayMode {
  listLoop,    // 列表循环
  singleLoop,  // 单曲循环
  random,      // 随机播放
  sequence     // 顺序播放
}

// 播放状态枚举
enum PlayState {
  stopped,
  playing,
  paused,
  loading,
  error
}

class AudioPlayerService {
  static final AudioPlayerService _instance = AudioPlayerService._internal();
  factory AudioPlayerService() => _instance;
  AudioPlayerService._internal();

  final AudioPlayer _audioPlayer = AudioPlayer();
  final Random _random = Random();
  
  // 状态变量
  Song? _currentSong;
  List<Song> _playlist = [];
  int _currentIndex = 0;
  PlayMode _playMode = PlayMode.listLoop;
  PlayState _playState = PlayState.stopped;
  Duration _currentPosition = Duration.zero;
  Duration _totalDuration = Duration.zero;

  // Stream控制器，用于通知UI更新
  final StreamController<Song?> _currentSongController = StreamController<Song?>.broadcast();
  final StreamController<PlayState> _playStateController = StreamController<PlayState>.broadcast();
  final StreamController<Duration> _positionController = StreamController<Duration>.broadcast();
  final StreamController<Duration> _durationController = StreamController<Duration>.broadcast();
  final StreamController<PlayMode> _playModeController = StreamController<PlayMode>.broadcast();

  // Stream getters
  Stream<Song?> get currentSongStream => _currentSongController.stream;
  Stream<PlayState> get playStateStream => _playStateController.stream;
  Stream<Duration> get positionStream => _positionController.stream;
  Stream<Duration> get durationStream => _durationController.stream;
  Stream<PlayMode> get playModeStream => _playModeController.stream;

  // Getters
  Song? get currentSong => _currentSong;
  List<Song> get playlist => _playlist;
  int get currentIndex => _currentIndex;
  PlayMode get playMode => _playMode;
  PlayState get playState => _playState;
  Duration get currentPosition => _currentPosition;
  Duration get totalDuration => _totalDuration;

  // 初始化
  Future<void> initialize() async {
    // 监听播放位置变化
    _audioPlayer.onPositionChanged.listen((position) {
      _currentPosition = position;
      _positionController.add(position);
    });

    // 监听播放时长变化
    _audioPlayer.onDurationChanged.listen((duration) {
      _totalDuration = duration;
      _durationController.add(duration);
    });

    // 监听播放完成
    _audioPlayer.onPlayerComplete.listen((_) {
      _onSongComplete();
    });

    // 监听播放状态变化
    _audioPlayer.onPlayerStateChanged.listen((state) {
      switch (state) {
        case PlayerState.playing:
          _updatePlayState(PlayState.playing);
          break;
        case PlayerState.paused:
          _updatePlayState(PlayState.paused);
          break;
        case PlayerState.stopped:
          _updatePlayState(PlayState.stopped);
          break;
        case PlayerState.completed:
          _updatePlayState(PlayState.stopped);
          break;
        case PlayerState.disposed:
          _updatePlayState(PlayState.stopped);
          break;
      }
    });

    print('AudioPlayerService: 初始化完成');
  }

  // 设置播放列表
  void setPlaylist(List<Song> songs, {int startIndex = 0}) {
    _playlist = songs;
    _currentIndex = startIndex.clamp(0, songs.length - 1);
    if (songs.isNotEmpty) {
      _currentSong = songs[_currentIndex];
      _currentSongController.add(_currentSong);
    }
    print('AudioPlayerService: 设置播放列表，共${songs.length}首歌曲');
  }

  // 播放指定歌曲
  Future<void> playSong(Song song) async {
    try {
      _updatePlayState(PlayState.loading);
      
      // 在播放列表中查找歌曲
      final index = _playlist.indexWhere((s) => s.id == song.id);
      if (index != -1) {
        _currentIndex = index;
      } else {
        // 如果不在播放列表中，添加到列表
        _playlist.add(song);
        _currentIndex = _playlist.length - 1;
      }

      _currentSong = song;
      _currentSongController.add(_currentSong);

      if (song.path != null && song.path!.isNotEmpty) {
        await _audioPlayer.setSourceDeviceFile(song.path!);
        await _audioPlayer.resume();
        print('AudioPlayerService: 开始播放 ${song.name} - ${song.artist}');
      } else {
        print('AudioPlayerService: 歌曲路径为空，无法播放');
        _updatePlayState(PlayState.error);
      }
    } catch (e) {
      print('AudioPlayerService: 播放失败 - $e');
      _updatePlayState(PlayState.error);
    }
  }

  // 播放指定位置的歌曲
  Future<void> playSongAtIndex(int index) async {
    if (index >= 0 && index < _playlist.length) {
      _currentIndex = index;
      await playSong(_playlist[index]);
    }
  }

  // 播放/暂停切换
  Future<void> togglePlayPause() async {
    if (_playState == PlayState.playing) {
      await pause();
    } else if (_playState == PlayState.paused) {
      await resume();
    } else if (_currentSong != null) {
      await playSong(_currentSong!);
    }
  }

  // 暂停
  Future<void> pause() async {
    await _audioPlayer.pause();
    print('AudioPlayerService: 暂停播放');
  }

  // 继续播放
  Future<void> resume() async {
    await _audioPlayer.resume();
    print('AudioPlayerService: 继续播放');
  }

  // 停止
  Future<void> stop() async {
    await _audioPlayer.stop();
    _currentPosition = Duration.zero;
    _positionController.add(_currentPosition);
    print('AudioPlayerService: 停止播放');
  }

  // 上一首
  Future<void> previousSong() async {
    switch (_playMode) {
      case PlayMode.listLoop:
      case PlayMode.sequence:
        if (_currentIndex > 0) {
          _currentIndex--;
        } else {
          _currentIndex = _playlist.length - 1;
        }
        break;
      case PlayMode.singleLoop:
        // 单曲循环：重新播放当前歌曲
        await seek(Duration.zero);
        return;
      case PlayMode.random:
        _currentIndex = _random.nextInt(_playlist.length);
        break;
    }

    if (_playlist.isNotEmpty) {
      await playSong(_playlist[_currentIndex]);
    }
  }

  // 下一首
  Future<void> nextSong() async {
    switch (_playMode) {
      case PlayMode.listLoop:
        if (_currentIndex < _playlist.length - 1) {
          _currentIndex++;
        } else {
          _currentIndex = 0;
        }
        break;
      case PlayMode.sequence:
        if (_currentIndex < _playlist.length - 1) {
          _currentIndex++;
        } else {
          // 顺序播放完毕，停止
          await stop();
          return;
        }
        break;
      case PlayMode.singleLoop:
        // 单曲循环：重新播放当前歌曲
        await seek(Duration.zero);
        return;
      case PlayMode.random:
        _currentIndex = _random.nextInt(_playlist.length);
        break;
    }

    if (_playlist.isNotEmpty) {
      await playSong(_playlist[_currentIndex]);
    }
  }

  // 跳转到指定位置
  Future<void> seek(Duration position) async {
    await _audioPlayer.seek(position);
    print('AudioPlayerService: 跳转到 ${position.inSeconds}秒');
  }

  // 设置播放模式
  void setPlayMode(PlayMode mode) {
    _playMode = mode;
    _playModeController.add(_playMode);
    print('AudioPlayerService: 切换播放模式为 $_playMode');
  }

  // 切换播放模式
  void togglePlayMode() {
    switch (_playMode) {
      case PlayMode.listLoop:
        setPlayMode(PlayMode.singleLoop);
        break;
      case PlayMode.singleLoop:
        setPlayMode(PlayMode.random);
        break;
      case PlayMode.random:
        setPlayMode(PlayMode.sequence);
        break;
      case PlayMode.sequence:
        setPlayMode(PlayMode.listLoop);
        break;
    }
  }

  // 设置音量 (0.0 - 1.0)
  Future<void> setVolume(double volume) async {
    await _audioPlayer.setVolume(volume.clamp(0.0, 1.0));
  }

  // 获取播放模式图标
  String getPlayModeIcon() {
    switch (_playMode) {
      case PlayMode.listLoop:
        return '🔁'; // 列表循环
      case PlayMode.singleLoop:
        return '🔂'; // 单曲循环
      case PlayMode.random:
        return '🔀'; // 随机播放
      case PlayMode.sequence:
        return '➡️'; // 顺序播放
    }
  }

  // 获取播放模式描述
  String getPlayModeDescription() {
    switch (_playMode) {
      case PlayMode.listLoop:
        return '列表循环';
      case PlayMode.singleLoop:
        return '单曲循环';
      case PlayMode.random:
        return '随机播放';
      case PlayMode.sequence:
        return '顺序播放';
    }
  }

  // 歌曲播放完成处理
  void _onSongComplete() {
    print('AudioPlayerService: 歌曲播放完成');
    
    switch (_playMode) {
      case PlayMode.listLoop:
      case PlayMode.random:
      case PlayMode.sequence:
        nextSong();
        break;
      case PlayMode.singleLoop:
        // 单曲循环：重新播放
        seek(Duration.zero);
        break;
    }
  }

  // 更新播放状态
  void _updatePlayState(PlayState state) {
    _playState = state;
    _playStateController.add(_playState);
  }

  // 释放资源
  void dispose() {
    _audioPlayer.dispose();
    _currentSongController.close();
    _playStateController.close();
    _positionController.close();
    _durationController.close();
    _playModeController.close();
    print('AudioPlayerService: 资源已释放');
  }
} 